<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article# " lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>kivy-ch8-shaders-app | 绿萝间</title>
<link href="../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<link href="../assets/css/ipython.min.css" rel="stylesheet" type="text/css">
<link href="../assets/css/nikola_ipython.css" rel="stylesheet" type="text/css">
<meta name="theme-color" content="#5670d4">
<meta name="generator" content="Nikola (getnikola.com)">
<link rel="alternate" type="application/rss+xml" title="RSS" href="../rss.xml">
<link rel="canonical" href="https://muxuezi.github.io/posts/kivy-ch8-shaders-app.html">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script><!--[if lt IE 9]><script src="../assets/js/html5.js"></script><![endif]--><meta name="author" content="Tao Junjie">
<link rel="prev" href="frequentism-and-bayesianism-chs-iii.html" title="frequentism-and-bayesianism-chs-iii" type="text/html">
<link rel="next" href="kivy-perface.html" title="kivy-perface" type="text/html">
<meta property="og:site_name" content="绿萝间">
<meta property="og:title" content="kivy-ch8-shaders-app">
<meta property="og:url" content="https://muxuezi.github.io/posts/kivy-ch8-shaders-app.html">
<meta property="og:description" content="着色器app¶








恭喜你Hold到现在！最后两章我们准备讨论一些OpenGL的底层细节，与Kivy完全不同的内容，比如OpenGL着色器语言（OpenGL Shading Language，GLSL）。这个语言可以让我们轻松写出高性能的代码。
我们将通过一个屏幕保护程序来介绍OpenGL的特性，然后做一个射击游戏（shoot-em-up game，shmup）app。本章的代码是准备">
<meta property="og:type" content="article">
<meta property="article:published_time" content="2015-06-24T13:43:08+08:00">
<meta property="article:tag" content="CHS">
<meta property="article:tag" content="ipython">
<meta property="article:tag" content="Kivy">
<meta property="article:tag" content="Python">
</head>
<body>
<a href="#content" class="sr-only sr-only-focusable">Skip to main content</a>

<!-- Menubar -->

<nav class="navbar navbar-inverse navbar-static-top"><div class="container">
<!-- This keeps the margins nice -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://muxuezi.github.io/">

                <span id="blog-title">绿萝间</span>
            </a>
        </div>
<!-- /.navbar-header -->
        <div class="collapse navbar-collapse" id="bs-navbar" aria-expanded="false">
            <ul class="nav navbar-nav">
<li>
<a href="../archive.html">Archive</a>
                </li>
<li>
<a href="../categories/">Tags</a>
                </li>
<li>
<a href="../rss.xml">RSS feed</a>

                
            </li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
    <a href="kivy-ch8-shaders-app.ipynb" id="sourcelink">Source</a>
    </li>

                
            </ul>
</div>
<!-- /.navbar-collapse -->
    </div>
<!-- /.container -->
</nav><!-- End of Menubar --><div class="container" id="content" role="main">
    <div class="body-content">
        <!--Body content-->
        <div class="row">
            
            
<article class="post-text h-entry hentry postpage" itemscope="itemscope" itemtype="http://schema.org/Article"><header><h1 class="p-name entry-title" itemprop="headline name"><a href="#" class="u-url">kivy-ch8-shaders-app</a></h1>

        <div class="metadata">
            <p class="byline author vcard"><span class="byline-name fn">
                    Tao Junjie
            </span></p>
            <p class="dateline"><a href="#" rel="bookmark"><time class="published dt-published" datetime="2015-06-24T13:43:08+08:00" itemprop="datePublished" title="2015-06-24 13:43">2015-06-24 13:43</time></a></p>
            
        <p class="sourceline"><a href="kivy-ch8-shaders-app.ipynb" id="sourcelink">Source</a></p>

        </div>
        

    </header><div class="e-content entry-content" itemprop="articleBody text">
    <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="着色器app">着色器app<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E7%9D%80%E8%89%B2%E5%99%A8app">¶</a>
</h2>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>恭喜你Hold到现在！最后两章我们准备讨论一些OpenGL的底层细节，与Kivy完全不同的内容，比如<strong>OpenGL着色器语言（OpenGL Shading Language，GLSL）</strong>。这个语言可以让我们轻松写出高性能的代码。</p>
<p>我们将通过一个屏幕保护程序来介绍OpenGL的特性，然后做一个射击游戏（shoot-em-up game，shmup）app。本章的代码是准备工作，和其他项目都是一章不同，射击游戏在下一章做。</p>
<!-- TEASER_END-->
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>本章会讨论很多复杂的问题，不过由于篇幅不能面面俱到，建议阅读OpenGL最新文档，因为OpenGL是一个标准，更新很快，新特性不断被加入，希望你在阅读的时候及时留意OpenGL相关的进展。</p>
<p>首先要讨论的是高性能着色器方法，尽管和普通的Kivy代码差别不大，而且两者大部分都相互兼容，在很多部件中都可以互相替代。因此，这种方法主要是用GLSL实现于资源消耗很大、性能要求很高的部分，消除性能的瓶颈。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="OpenGL简介">OpenGL简介<a class="anchor-link" href="kivy-ch8-shaders-app.html#OpenGL%E7%AE%80%E4%BB%8B">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在让我们简单介绍下OpenGL。OpenGL是一个底层的图像API，其标准被广泛采用。桌面系统和移动系统均支持（在移动系统上是OpenGL ES，<strong>Embedded Systems，嵌入式系统</strong>）。现代浏览器也支持OpenGL ES的一个分支版本，就是大名鼎鼎的WebGL。</p>
<p>OpenGL的广泛采用使其具有良好的跨平台能力，尤其在视频游戏和图形编程方面。Kivy的跨平台着色器同样依赖于OpenGL。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="并行方式">并行方式<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%B9%B6%E8%A1%8C%E6%96%B9%E5%BC%8F">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>OpenGL可以操纵基本的图形元素，如单个的点和屏幕上的每个像素。我们可以画三个点，然后构成一个三角形，计算每个像素的应该填充的颜色。你可能认为这种做法是非常麻烦的。这正是像kivy这样的高级图形框架出现的原因：它们都隐藏了OpenGL的管线（pipeline）的一堆细节，提供组件和布局来简化操作。复杂底层的管线功能如下图所示：</p>
<p><img src="kbpic/8.1%20pipeline.png" alt="pipeline"></p>
<p>这个复杂的图形包括以下四个方面：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<ul>
<li>应用给OpenGL一个点数组（vertices），可以重用这些点的索引数组（indices），以及其他数值（uniforms）</li>
<li>对每个点进行点着色器（vertex shader），根据需要做一系列计算。然后输出到片段着色器（fragment shader）</li>
<li>对每个像素进行分段着色器（也叫像素着色器，pixel shader），计算像素的颜色。有时除了点着色器的输出结果，还要考虑一个颜色常量</li>
<li>像素被着色器到屏幕上，其他的一些任务被完成，这些任务我们暂不讨论</li>
</ul>
<blockquote>
<p>上面使用的一组点称为模型（model）或网格（mesh）。它们不一定是连续的，也可能是离散的多边形；这些模型的理论基础后面会介绍。</p>
</blockquote>
<p>OpenGL超快速度的背后是大量并行计算方法的使用。上面提到的点着色器和像素着色器可能不会自动飞快运行，但是当通过GPU加速的瞬间，着色器造成的延迟并不会随着着色复杂度的增加呈指数级增长；在正常的硬件上其增速基本是线性的。</p>
<p>对应到现实中，我们讨论的，就是今天用2-16核CPU的电脑进行多任务、并行编程的个人电脑。一般的中档显卡，也有几千个GPU核心，可以并行处理更多的计算。</p>
<p>每个任务都是独立运行的，不像一般程序里面的线程，着色器不能等待其他任务完成再运行，这样会出现阻塞且严重影响性能，除了使用管线命令的时候（就像前面提到的，先进行点着色器，再运行像素着色器）。这种限制在你刚刚接触GLSL的时候，可能有点难理解。</p>
<p>这就是为什么有些算法可以在GPU上面非常高效。现代加密算法像<strong>bcrypt</strong>就是用来限制这种高并发性能的——通过限制暴力破解能力来保障安全性。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="性能得失">性能得失<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E6%80%A7%E8%83%BD%E5%BE%97%E5%A4%B1">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>并非只有原始的OpenGL才可以获得极快的性能。很多时候，像Kivy这样的高级框架也可以如此。比如，当你在屏幕上着色器多边形的时候，下面的一系列动作就会发生：</p>
<ul>
<li>用python定义多边形的形状和位置</li>
<li>点，索引数组和相关的资源（如花纹）都上传到图像接口</li>
<li>调用点着色器功能，进行定位、着色、缩放等变换</li>
<li>最后，调用像素着色器功能，返回一个栅格图像显示到屏幕上</li>
</ul>
<p>无论你是要Kivy部件还是用原始的OpenGL命令和GLSL着色器，两种方式的性能都是一样的。这是因为Kivy底层和OpenGL类似。</p>
<p>也就是说，底层优化其实没多大必要，这就是由几个矩形构成的<em>Kivy Bird</em>游戏，可以直接通过高级接口实现的原因。基本上，我们可以在<em>Kivy Bird</em>里优化一两个部件，但是其性能很难被察觉。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="改善性能">改善性能<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E6%94%B9%E5%96%84%E6%80%A7%E8%83%BD">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>那么，性能到底如何改善呢？答案就是减少Python代码，精简着色器内容。假如我们要着色9,000个相似的多边形（比如秋天的落叶或漫天的行程）。如果每个多边形都用一个Kivy部件，那我们就要做很多个Python对象，要被单独序列化成OpenGL指令。另外，每个部件都有点集合相关的图像接口，必然产生大量的API调用，还有许多类似的匹配（mesh）。</p>
<p>我们可以做两件事来优化：</p>
<ul>
<li>避免大量Python类实例，把它们放在一个数值中即可。如果储存成一个适合OpenGL处理的格式中，就可以免掉序列化的步骤</li>
<li>把所有的图形组合到一起作为一个单独模型处理，这样可以减少API调用。批处理通常是很好的优化方法，因为它让OpenGL以并行方式更好的运行。</li>
</ul>
<p>在本章结束的时候我们会实现这些方法。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="GLSL介绍">GLSL介绍<a class="anchor-link" href="kivy-ch8-shaders-app.html#GLSL%E4%BB%8B%E7%BB%8D">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>GLSL作为一门语言，与C语法类似，是一个静态强类型。如果你不熟悉C语言，下面是参考。C与Python不同，不在乎缩进，句末要用分号，逻辑代码块要用括号。</p>
<p>GLSL同时支持C和C++的注释方式：</p>
<div class="highlight"><pre><span></span><span class="cm">/* ANSI C-style comment */</span>
<span class="c1">// C++ one-line comment</span>
</pre></div>
<p>变量声明方式为<code>[type] [name] [= optional value];</code>：</p>
<div class="highlight"><pre><span></span><span class="kt">float</span> <span class="n">a</span><span class="p">;</span> <span class="c1">// this has no direct Python equivalent</span>
<span class="kt">int</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</pre></div>
<p>函数定义方式为<code>[type] [name] ([arguments]) { [body of function] }</code>：</p>
<div class="highlight"><pre><span></span><span class="kt">float</span> <span class="nf">pow2</span><span class="p">(</span><span class="kt">float</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>控制结构形式为：</p>
<div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">x</span> <span class="o">&lt;</span> <span class="mf">9.0</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">x</span> <span class="o">=</span> <span class="mf">9.0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>差不多就这些了，即使没有学过C，你现在也可以读GLSL代码了。</p>
<p>着色器代码的起点是<code>main()</code>函数。后面，我们把点着色器和像素着色器放在一个文件中，因此，在一个文件里面会有两个<code>main()</code>函数。其结构如下：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// code</span>
<span class="p">}</span>
</pre></div>
<p>这里的<code>void</code>类型表示函数没有返回值，和Python的<code>NoneType</code>不一样，你不能把变量声明为<code>void</code>类型。这里的两个<code>main()</code>函数返回值和参数都被忽略了，所以写成<code>void main(void)</code>。着色器会根据需要把结果写到内部变量，<code>gl_Position</code>，<code>gl_FragColor</code>和其他变量里面，不需要返回数据结果，输入参数为空也是同理。</p>
<p>GLSL类型系统完全反映了它的作用。不像C语言，它为点和矩阵准备了专门的类型，这些类型支持数学运算（所以你可以直接对矩阵变量进行乘法<code>mat1 * mat2</code>，多简单啊！C一个试试就知道C多麻烦了）。在计算机图形学里，矩阵计算不可或缺，后面会介绍。</p>
<p>下面，我们就来写几个GLSL的例子。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="在Kivy中自定义着色器">在Kivy中自定义着色器<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%9C%A8Kivy%E4%B8%AD%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9D%80%E8%89%B2%E5%99%A8">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>首先我们需要用Python代码实现窗口、加载着色器等等。代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">kivy.app</span> <span class="k">import</span> <span class="n">App</span>
<span class="kn">from</span> <span class="nn">kivy.base</span> <span class="k">import</span> <span class="n">EventLoop</span>
<span class="kn">from</span> <span class="nn">kivy.graphics</span> <span class="k">import</span> <span class="n">Mesh</span>
<span class="kn">from</span> <span class="nn">kivy.graphics.instructions</span> <span class="k">import</span> <span class="n">RenderContext</span>
<span class="kn">from</span> <span class="nn">kivy.uix.widget</span> <span class="k">import</span> <span class="n">Widget</span>

<span class="k">class</span> <span class="nc">GlslDemo</span><span class="p">(</span><span class="n">Widget</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">Widget</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span> <span class="o">=</span> <span class="n">RenderContext</span><span class="p">(</span><span class="n">use_parent_projection</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="o">.</span><span class="n">shader</span><span class="o">.</span><span class="n">source</span> <span class="o">=</span> <span class="s1">'basic.glsl'</span>
        <span class="c1"># Set up geometry here.</span>
        
<span class="k">class</span> <span class="nc">GlslApp</span><span class="p">(</span><span class="n">App</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">build</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">EventLoop</span><span class="o">.</span><span class="n">ensure_window</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">GlslDemo</span><span class="p">()</span>
    
<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">'__main__'</span><span class="p">:</span>
    <span class="n">GlslApp</span><span class="p">()</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这么我们创建了一个部件<code>GlslDemo</code>；用来管理所有的渲染。<code>RenderContext</code>是<code>Canvas</code>的子类用来轻松替换着色器。<code>basic.glsl</code>文件包含点着色器和像素着色器，后面会实现。</p>
<p>注意我们没用Kivy语言，因为没有布局要使用，所以这里不是<code>glsl.kv</code>文件，我们通过<code>GlslApp.build()</code>方法配置根部件。</p>
<p><code>EventLoop.ensure_window()</code>是必须的，因为我们需要接入OpenGL特性，包括在运行<code>GlslDemo.__init__()</code>方法时，调用GLSL编译器。如果此时没有应用窗口（更重要的是，没有相关的OpenGL内容），程序就会崩溃。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="建立几何图形">建立几何图形<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%BB%BA%E7%AB%8B%E5%87%A0%E4%BD%95%E5%9B%BE%E5%BD%A2">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>写着色器之前，我们还需要渲染一些东西——一系列点模型。我们用两个等斜边的直角三角形构成一个简单的矩形（这么分是因为基本多边形是三角形）。</p>
<blockquote>
<p>Kivy更偏向于二维图形，所以在二维设计中不会强加任何限制。而OpenGL是源自三维图形，所以你可以用生动的模型来创建视频游戏，也可以结合Kivy的部件来创建UI。本书不做介绍，但是两者底层的机制是一样的。</p>
</blockquote>
<p>这里需要升级<code>GlslDemo</code>部件里的<code>__init__()</code>方法：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">Widget</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span> <span class="o">=</span> <span class="n">RenderContext</span><span class="p">(</span><span class="n">use_parent_projection</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="o">.</span><span class="n">shader</span><span class="o">.</span><span class="n">source</span> <span class="o">=</span> <span class="s1">'basic.glsl'</span>
    
    <span class="n">fmt</span> <span class="o">=</span> <span class="p">(</span> <span class="c1"># Step 1</span>
        <span class="p">(</span><span class="sa">b</span><span class="s1">'vPosition'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
    <span class="p">)</span>
    
    <span class="n">vertices</span> <span class="o">=</span> <span class="p">(</span> <span class="c1"># Step 2</span>
        <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
        <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
        <span class="mi">255</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span>
        <span class="mi">0</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span>
    <span class="p">)</span>
    
    <span class="n">indices</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="c1"># Step 3</span>
    
    <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="p">:</span>
        <span class="n">Mesh</span><span class="p">(</span><span class="n">fmt</span><span class="o">=</span><span class="n">fmt</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">'triangles'</span><span class="p">,</span> <span class="c1"># Step 4</span>
            <span class="n">indices</span><span class="o">=</span><span class="n">indices</span><span class="p">,</span> <span class="n">vertices</span><span class="o">=</span><span class="n">vertices</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>方法解释如下：</p>
<ul>
<li>写<code>OpenGL</code>代码时需要注意点对象没有标准的格式，因此，我们需要定义一个。简单的做法就是用点的位置<code>vPosition</code>。我们的矩形是二维的，因此我们就传递两个坐标，默认是浮点型数值。因此，定义是<code>(b'vPosition', 2, 'float')</code>
</li>
<li>确定了点的格式之后，我们把这些点放到一个数组里，如<code>vertices = (...)</code>行所示。这个元组只有一层，后面会单独定义记录的格式，然后再把所有值聚合在一起，没有用分隔符或其他类似好记的名称。这是C语言结构体的经典方式</li>
<li>索引数组用来复用那些顶点。通常，一个顶点被多个三角形同时使用。我们使用索引数组里的index来重复使用这些顶点——这样顶点数增加时内存占用相对更少</li>
<li>有了这些数据结构之后，我们就用类似Kivy画布指令的<code>Mesh</code>把它们组合起来。它按照通常部件渲染的方式进行渲染，和其他Kivy部件有很好的兼容性。GLSL代码可以用来连接所有的部分</li>
</ul>
<blockquote>
<p>这章提到了一个C语言概念，<code>array（数组）</code>——存放同类数据的连续内存区域。Python数据结构里也有，不过，Python通常用<code>tuple（元组）</code>或<code>list（列表）</code>。</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="解释索引">解释索引<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E8%A7%A3%E9%87%8A%E7%B4%A2%E5%BC%95">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>要理解OpenGL的索引（index），让我们举个例子。用前面代码里面的顶点，是按照<code>(x, y)</code>存放的：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">vertices</span> <span class="o">=</span> <span class="p">(</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>一个索引就是顶点列表里面的顶点数据，原点是<code>(0, 0)</code>。如下图所示：</p>
<p><img src="kbpic/8.2%20openglindex.png" alt="openglindex"></p>
<p>现在顶点还没有连起来，所以显示出来就是一些点，而不是一个多边形。我们定义一个<code>indices</code>列表来组合它们。三个点两组构成两个三角形：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">indices</span> <span class="o">=</span> <span class="p">(</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="c1"># 三个点构成一个三角形</span>
    <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="c1"># 另一个三角形</span>
<span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这两个三角形中，第一个是由顶点0，1，2构成，第二个是由订单2，3，0构成。如下图所示，颜色是展示用的，我们还没有设置颜色，后面会补上。</p>
<p><img src="kbpic/8.3%20triangles.png" alt="triangles"></p>
<p>OpenGL代码里面的索引就是这样使用的。</p>
<blockquote>
<p>OpenGL数据结构内存优化方法中很少是专门用来减少RAM的——很多时候视频接口吞吐量是性能的瓶颈，所以优化的目标都是每帧传递更多的内容，而不是通过压缩数据来节省内存。这点自始至终没有改变过。</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="写GLSL代码">写GLSL代码<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%86%99GLSL%E4%BB%A3%E7%A0%81">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>下面我们就来写可以在GPU上执行的GLSL代码，它和C语言一样快。</p>
<p>Kviy要求点着色器和像素着色器代码在一个文件里，代码用<code>'---vertex'</code>和<code>'---fragment'</code>分割，<code>$HEADER$</code>语句由Kivy指定，这并非任何标准，只在这里用：</p>
<div class="highlight"><pre><span></span><span class="o">---</span><span class="n">vertex</span>
<span class="err">$</span><span class="n">HEADER</span><span class="err">$</span>

<span class="kt">void</span> <span class="n">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// vertex shader</span>
    <span class="n">gl_Position</span> <span class="o">=</span> <span class="p">...</span>
<span class="p">}</span>

<span class="o">---</span><span class="n">fragment</span>
<span class="err">$</span><span class="n">HEADER</span><span class="err">$</span>

<span class="kt">void</span> <span class="n">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// fragment shader</span>
    <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="p">...</span>
<span class="p">}</span>
</pre></div>
<p>为了节省篇幅，后面的代码会忽略这些样本代码，希望你看代码的时候记得它们是存在的。</p>
<p><code>$HEADER$</code>宏变量是上下文相关的，表示不同类型的着色器。</p>
<p>在点着色器里面，<code>$HEADER$</code>是下面代码：</p>
<div class="highlight"><pre><span></span><span class="n">varying</span> <span class="n">vec4</span> <span class="n">frag_color</span><span class="p">;</span>
<span class="n">varying</span> <span class="n">vec2</span> <span class="n">tex_coord0</span><span class="p">;</span>
<span class="n">attribute</span> <span class="n">vec2</span> <span class="n">vPosition</span><span class="p">;</span>
<span class="n">attribute</span> <span class="n">vec2</span> <span class="n">vTexCoords0</span><span class="p">;</span>
<span class="n">uniform</span> <span class="n">mat4</span> <span class="n">modelview_mat</span><span class="p">;</span>
<span class="n">uniform</span> <span class="n">mat4</span> <span class="n">projection_mat</span><span class="p">;</span>
<span class="n">uniform</span> <span class="n">vec4</span> <span class="n">color</span><span class="p">;</span>
<span class="n">uniform</span> <span class="kt">float</span> <span class="n">opacity</span><span class="p">;</span>
</pre></div>
<p>在像素着色器里面，<code>$HEADER$</code>是下面代码：</p>
<div class="highlight"><pre><span></span><span class="n">varying</span> <span class="n">vec4</span> <span class="n">frag_color</span><span class="p">;</span>
<span class="n">varying</span> <span class="n">vec2</span> <span class="n">tex_coord0</span><span class="p">;</span>

<span class="n">uniform</span> <span class="n">sampler2D</span> <span class="n">texture0</span><span class="p">;</span>
</pre></div>
<p>有点啰嗦，以后的Kivy版本应该会简化它们。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="存储类与类型">存储类与类型<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%AD%98%E5%82%A8%E7%B1%BB%E4%B8%8E%E7%B1%BB%E5%9E%8B">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在前面的代码里，不仅有数据类型，还有一个存储类：</p>
<ul>
<li>存储类（Storage classes）<ul>
<li>
<code>attribute</code>：由点数据格式指定对应每个点的属性，由应用传递</li>
<li>
<code>uniform</code>：GLSL全局变量，同样由应用传递，但是不会随点变化</li>
<li>
<code>varying</code>：有点着色器传递到像素着色器</li>
</ul>
</li>
<li>常用数据类型（Commonly used data types）<ul>
<li>
<code>float</code>：浮点类型</li>
<li>
<code>vec2, vec3, vec4</code>：长度为2，3，4的元组类型，内部值为浮点类型。可以表示点、颜色等等</li>
<li>
<code>mat2, mat3, mat4</code>：规模为 2 × 2，3 × 3，4 × 4的矩阵类型，</li>
<li>
<code>sampler2D</code>：表示一个用来装饰的纹理（texture）类型</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="基本着色器">基本着色器<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%9F%BA%E6%9C%AC%E7%9D%80%E8%89%B2%E5%99%A8">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>现在，让我们来写一个简单的着色器：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">vec4</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">vPosition</span><span class="p">.</span><span class="n">xy</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
    <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">projection_mat</span> <span class="o">*</span> <span class="n">modelview_mat</span> <span class="o">*</span> <span class="n">pos</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>把每个点的坐标值转换成Kivy系统的坐标值，其原点在左下角。</p>
<blockquote>
<p>这里不演示坐标变换的细节，作为入门教程有点复杂。其实也没必要完全理解这些细节，或者读完整本书。
如果你很感兴趣，可以去看看<a href="http://www.learnopengles.com/understanding-opengls-matrices/">OpenGL的坐标空间和矩阵用法</a></p>
</blockquote>
<p>最简单的像素着色器就是一个返回固定颜色的函数：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>这里为每个点返回一个RGBA颜色值<code>#FF007F</code>。</p>
<p>如果你运行程序，你会看到输出结果如下图所示：</p>
<p><img src="kbpic/8.4%20basicshaders.png" alt="basicshaders"></p>
<p>聊胜于无，折腾这么久，终于有点儿成果了，下面我们调整一下看看变化。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="程序的颜色">程序的颜色<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E7%A8%8B%E5%BA%8F%E7%9A%84%E9%A2%9C%E8%89%B2">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>除了显示一种颜色外，颜色还有可以通过另一个方法让像素着色器显示出来。</p>
<p>假设我们想要计算每个像素的RGB颜色：</p>
<ul>
<li>
<code>R</code>通道值与<code>x</code>轴坐标成正比</li>
<li>
<code>G</code>通道值与<code>y</code>轴坐标成正比</li>
<li>
<code>B</code>通道值等于<code>R</code>与<code>G</code>均值</li>
</ul>
<p>对应最简单像素着色器的算法如下：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">float</span> <span class="n">r</span> <span class="o">=</span> <span class="n">gl_FragCoord</span><span class="p">.</span><span class="n">x</span> <span class="o">/</span> <span class="mf">255.0</span><span class="p">;</span>
    <span class="kt">float</span> <span class="n">g</span> <span class="o">=</span> <span class="n">gl_FragCoord</span><span class="p">.</span><span class="n">y</span> <span class="o">/</span> <span class="mf">255.0</span><span class="p">;</span>
    <span class="kt">float</span> <span class="n">b</span> <span class="o">=</span> <span class="mf">0.5</span> <span class="o">*</span> <span class="p">(</span><span class="n">r</span> <span class="o">+</span> <span class="n">g</span><span class="p">);</span>
    <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">g</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p><code>gl_FragCoord</code>变量包括相对于应用窗口的像素坐标值（并非实际屏幕的坐标值）。这里除以<code>255.0</code>是为了简化计算，让所有的值都落在[0，1]区间内。</p>
<p>效果图像如下：</p>
<p><img src="kbpic/8.5%20computingcolor.png" alt="computingcolor"></p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="彩色顶点">彩色顶点<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%BD%A9%E8%89%B2%E9%A1%B6%E7%82%B9">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>类似的彩色效果可以通过给点增加颜色数据来实现。因此，我们需要扩展点的数据格式，增加一个带颜色的属性<code>vColor</code>：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">fmt</span> <span class="o">=</span> <span class="p">(</span>
    <span class="p">(</span><span class="sa">b</span><span class="s1">'vPosition'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
    <span class="p">(</span><span class="sa">b</span><span class="s1">'vColor'</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
<span class="p">)</span>

<span class="n">vertices</span> <span class="o">=</span> <span class="p">(</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mf">0.462</span><span class="p">,</span> <span class="mf">0.839</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mf">0.831</span><span class="p">,</span> <span class="mf">0.984</span><span class="p">,</span> <span class="mf">0.474</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">0.541</span><span class="p">,</span> <span class="mf">0.847</span><span class="p">,</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">0.988</span><span class="p">,</span> <span class="mf">0.474</span><span class="p">,</span>
<span class="p">)</span>

<span class="n">indices</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>更新之后，每个点都有5个维度，后面三个是RGB颜色值。对应的<code>vertices</code>也要做修改。</p>
<p><code>vColor</code>属性是一个RGB颜色值，而点着色器用的是RGBA颜色，这里并没有每个点的alpha通道值，我们需要对点着色器做一些调整：</p>
<div class="highlight"><pre><span></span><span class="n">attribute</span> <span class="n">vec3</span> <span class="n">vColor</span><span class="p">;</span>

<span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">frag_color</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">vColor</span><span class="p">.</span><span class="n">rgb</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
    <span class="n">vec4</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">vPosition</span><span class="p">.</span><span class="n">xy</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
    <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">projection_mat</span> <span class="o">*</span> <span class="n">modelview_mat</span> <span class="o">*</span> <span class="n">pos</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<blockquote>
<p>在GLSL中，<code>vColor.rgb</code>和<code>vPosition.xy</code>表示法叫混合（swizzling）。它们可以有效的获取矢量的一部分，类似于Python的切片（slice）。</p>
<p>这里的<code>vColor.rgb</code>表示“取矢量的前三个值”，在Python里面就是<code>vColor[:3]</code>。还可以颠倒顺序，如<code>vColor.bgr</code>，甚至重复，如<code>vColor.ggg</code>（取三个<code>G</code>通道值），样式很灵活。</p>
<p>同理，可以取矢量的四个值，如<code>.xyzw</code>，<code>.rgba</code>或<code>.stpq</code>。</p>
</blockquote>
<p>那么，像素着色器就很简单了：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">frag_color</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>让点与点之间的颜色插值计算，就呈现平滑渐变的效果了，这就是OpenGL的工作方式，如下图所示：</p>
<p><img src="kbpic/8.6%20passingcolor.png" alt="passingcolor"></p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h5 id="纹理映射">纹理映射<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E7%BA%B9%E7%90%86%E6%98%A0%E5%B0%84">¶</a>
</h5>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>下面再给我们的矩形增加一些纹理。我们还要扩展点数据格式的定义，给每个点增加纹理坐标值：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">fmt</span> <span class="o">=</span> <span class="p">(</span>
    <span class="p">(</span><span class="sa">b</span><span class="s1">'vPosition'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
    <span class="p">(</span><span class="sa">b</span><span class="s1">'vTexCoords0'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
<span class="p">)</span>

<span class="n">vertices</span> <span class="o">=</span> <span class="p">(</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
    <span class="mi">255</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
    <span class="mi">0</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>纹理坐标值通常都在[0,1]区间内，原点在左上角，这和Kivy的左下角原点是不同的。使用过程中，需要注意这个差别。</p>
<p>下面是Python加载纹理并传递给渲染的过程：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">kivy.core.image</span> <span class="k">import</span> <span class="n">Image</span>

<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="p">:</span>
    <span class="n">Mesh</span><span class="p">(</span><span class="n">fmt</span><span class="o">=</span><span class="n">fmt</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">'triangles'</span><span class="p">,</span>
        <span class="n">indices</span><span class="o">=</span><span class="n">indices</span><span class="p">,</span> <span class="n">vertices</span><span class="o">=</span><span class="n">vertices</span><span class="p">,</span>
        <span class="n">texture</span><span class="o">=</span><span class="n">Image</span><span class="p">(</span><span class="s1">'kivy.png'</span><span class="p">)</span><span class="o">.</span><span class="n">texture</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这样就把当前文件夹内的<code>kivy.png</code>文件转换成纹理了。如下图所示：</p>
<p><img src="kbpic/8.7%20texture.png" alt="texture"></p>
<p>这和前面的着色器没啥不同。点着色器传递纹理的坐标值：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">tex_coord0</span> <span class="o">=</span> <span class="n">vTexCoords0</span><span class="p">;</span>
    <span class="n">vec4</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">vPosition</span><span class="p">.</span><span class="n">xy</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
    <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">projection_mat</span> <span class="o">*</span> <span class="n">modelview_mat</span> <span class="o">*</span> <span class="n">pos</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>像素着色器用修改过的<code>tex_coord0</code>坐标值来装饰在<code>texture0</code>位置的纹理，于是返回对应的颜色：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
   <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">texture2D</span><span class="p">(</span><span class="n">texture0</span><span class="p">,</span> <span class="n">tex_coord0</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>把代码放到一起就看可以到如下效果：</p>
<p><img src="kbpic/8.8%20texturemapping.png" alt="texturemapping"></p>
<p>通过着色器的实现经历，你可以去做一些相关程序了。如果有的地方不明白不用郁闷，GLSL确实比较复杂，系统的学习它得费一番功夫。</p>
<p>但是，它可以让你更清楚底层的工作细节。即使你日常工作中没写过底层代码，你也可以掌握这些知识，以避免性能瓶颈，改善程序的架构。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="做满天星app">做满天星app<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%81%9A%E6%BB%A1%E5%A4%A9%E6%98%9Fapp">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>学习了一堆GLSL的知识后，我们来做一个满天星屏保的app，星星会从屏幕的中央向四边飞来，给人一种穿越星空的快感。</p>
<blockquote>
<p>动态效果用图片没法展示，你可以直接运行实例代码看看效果。</p>
</blockquote>
<p>每颗星都会做如下动作：</p>
<ol>
<li>在屏幕中央随机生成</li>
<li>从屏幕中央向四周飞去直到看不见为止</li>
<li>然后从屏幕中央重新生成</li>
</ol>
<p>我们还会让星星的尺寸在飞行中不断变大。如下图所示：</p>
<p><img src="kbpic/8.9%20screenshot.png" alt="screenshot"></p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="应用架构">应用架构<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>新应用类的架构借用前面章节的内容即可。这里同样不用Kivy语言描述部件层级，所以没有<code>starfield.kv</code>。Python代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">kivy.base</span> <span class="k">import</span> <span class="n">EventLoop</span>
<span class="kn">from</span> <span class="nn">kivy.clock</span> <span class="k">import</span> <span class="n">Clock</span>

<span class="k">class</span> <span class="nc">StarfieldApp</span><span class="p">(</span><span class="n">App</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">build</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">EventLoop</span><span class="o">.</span><span class="n">ensure_window</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">Starfield</span><span class="p">()</span>
    
    <span class="k">def</span> <span class="nf">on_start</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">Clock</span><span class="o">.</span><span class="n">schedule_interval</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">root</span><span class="o">.</span><span class="n">update_glsl</span><span class="p">,</span><span class="mi">60</span> <span class="o">**</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这里<code>build()</code>方法创建并返回根部件<code>Starfield</code>；它将控制所有的数学和渲染应用中的内容。</p>
<p><code>on_start()</code>事件handler在程序启动后，让根部件通过<code>update_glsl()</code>方法实现每秒更新60次。</p>
<p><code>Starfield</code>类还分成两部分：<code>__init__()</code>方法用来创建数据结构，<code>update_glsl()</code>方法呈现图像（计算每颗星的位置）并渲染星星。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="数据结构与初始化">数据结构与初始化<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E5%88%9D%E5%A7%8B%E5%8C%96">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>初始化代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">kivy.core.image</span> <span class="k">import</span> <span class="n">Image</span>
<span class="kn">from</span> <span class="nn">kivy.graphics.instructions</span> <span class="k">import</span> <span class="n">RenderContext</span>
<span class="kn">from</span> <span class="nn">kivy.uix.widget</span> <span class="k">import</span> <span class="n">Widget</span>

<span class="n">NSTARS</span> <span class="o">=</span> <span class="mi">1000</span>

<span class="k">class</span> <span class="nc">Starfield</span><span class="p">(</span><span class="n">Widget</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">Widget</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span> <span class="o">=</span> <span class="n">RenderContext</span><span class="p">(</span><span class="n">use_parent_projection</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="o">.</span><span class="n">shader</span><span class="o">.</span><span class="n">source</span> <span class="o">=</span> <span class="s1">'starfield.glsl'</span>
        
        <span class="bp">self</span><span class="o">.</span><span class="n">vfmt</span> <span class="o">=</span> <span class="p">(</span>
            <span class="p">(</span><span class="sa">b</span><span class="s1">'vCenter'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
            <span class="p">(</span><span class="sa">b</span><span class="s1">'vScale'</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
            <span class="p">(</span><span class="sa">b</span><span class="s1">'vPosition'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
            <span class="p">(</span><span class="sa">b</span><span class="s1">'vTexCoords0'</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'float'</span><span class="p">),</span>
        <span class="p">)</span>
        
        <span class="bp">self</span><span class="o">.</span><span class="n">vsize</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">attr</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">attr</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">vfmt</span><span class="p">)</span>
        
        <span class="bp">self</span><span class="o">.</span><span class="n">indices</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">4</span> <span class="o">*</span> <span class="n">NSTARS</span><span class="p">,</span> <span class="mi">4</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">indices</span><span class="o">.</span><span class="n">extend</span><span class="p">((</span><span class="n">i</span><span class="p">,</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">2</span><span class="p">,</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">2</span><span class="p">,</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">3</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span>
            
        <span class="bp">self</span><span class="o">.</span><span class="n">vertices</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">NSTARS</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">vertices</span><span class="o">.</span><span class="n">extend</span><span class="p">((</span>
                <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">24</span><span class="p">,</span> <span class="o">-</span><span class="mi">24</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
                <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="o">-</span><span class="mi">24</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span>
                <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
                <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">24</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span>
            <span class="p">))</span>
            
        <span class="bp">self</span><span class="o">.</span><span class="n">texture</span> <span class="o">=</span> <span class="n">Image</span><span class="p">(</span><span class="s1">'star.png'</span><span class="p">)</span><span class="o">.</span><span class="n">texture</span>
        
        <span class="bp">self</span><span class="o">.</span><span class="n">stars</span> <span class="o">=</span> <span class="p">[</span><span class="n">Star</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">NSTARS</span><span class="p">)]</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>NSTARS</code>是星星的总数，调整它会改变星星的密度。一个带Intel集成显卡的中档电脑可以轻松支持几千个星星。再高档点的显卡带几万个星星也没问题。</p>
<p>和前面的例子不同，这次我们不在最后实现索引和点的数组。在初始化阶段我们就设置好，方便后面<code>update_glsl()</code>方法更新。</p>
<p><code>vfmt</code>顶点格式包括四个属性，如下表所示：</p>
<table>
<thead><tr>
<th style="text-align:center"><strong>属性</strong></th>
<th style="text-align:center"><strong>功能</strong></th>
</tr></thead>
<tbody>
<tr>
<td style="text-align:center"><code>vCenter</code></td>
<td style="text-align:center">星星中点在屏幕上的坐标值</td>
</tr>
<tr>
<td style="text-align:center"><code>vScale</code></td>
<td style="text-align:center">星星的尺寸，1表示（48 × 48 像素）</td>
</tr>
<tr>
<td style="text-align:center"><code>vPosition</code></td>
<td style="text-align:center">每个顶点与星星中点的相对位置</td>
</tr>
<tr>
<td style="text-align:center"><code>vTexCoords0</code></td>
<td style="text-align:center">纹理坐标值</td>
</tr>
</tbody>
</table>
<p>还有个属性<code>vsize</code>是顶点数组<code>vfmt</code>里的单个顶点的总长度。它计算顶点格式<code>vfmt</code>中间列的总和。</p>
<p><code>vertices</code>列表包含需要的数据；但它没有层次，不方便操作。这里就做了一个<code>Star</code>辅助类来实现，它把细节封装起来，在顶点数组外加了一个类，这样可以省不少事儿。</p>
<p><code>Star</code>类还会持续跟踪不属于顶点数据格式的一些属性，极坐标（以中心为原点的<code>angle</code>角度和<code>distance</code>距离）和不断增大的<code>size</code>。</p>
<p><code>Star</code>类定义如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">import</span> <span class="nn">math</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="k">import</span> <span class="n">random</span>

<span class="k">class</span> <span class="nc">Star</span><span class="p">:</span>
    <span class="n">angle</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">distance</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">size</span> <span class="o">=</span> <span class="mf">0.1</span>
    
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sf</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">sf</span> <span class="o">=</span> <span class="n">sf</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">base_idx</span> <span class="o">=</span> <span class="mi">4</span> <span class="o">*</span> <span class="n">i</span> <span class="o">*</span> <span class="n">sf</span><span class="o">.</span><span class="n">vsize</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
        
    <span class="k">def</span> <span class="nf">reset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">angle</span> <span class="o">=</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">*</span> <span class="n">random</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">distance</span> <span class="o">=</span> <span class="mi">90</span> <span class="o">*</span> <span class="n">random</span><span class="p">()</span> <span class="o">+</span> <span class="mi">10</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">size</span> <span class="o">=</span> <span class="mf">0.05</span> <span class="o">*</span> <span class="n">random</span><span class="p">()</span> <span class="o">+</span> <span class="mf">0.05</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>base_idx</code>是星星点数组的第一个顶点，还要加一个引用<code>sf</code>，方便<code>Starfield</code>实例连接<code>vertices</code>。</p>
<p><code>reset()</code>调用之后把星星的属性复原。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="推动图像">推动图像<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E6%8E%A8%E5%8A%A8%E5%9B%BE%E5%83%8F">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>Starfield.update_glsl()</code>方式实现了星星运动的算法，被<code>on_start()</code>事件handler的Kivy时钟程序频繁调用。源代码如下：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">kivy.graphics</span> <span class="k">import</span> <span class="n">Mesh</span>

<span class="k">def</span> <span class="nf">update_glsl</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nap</span><span class="p">):</span>
    <span class="n">x0</span><span class="p">,</span> <span class="n">y0</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">center</span>
    <span class="n">max_distance</span> <span class="o">=</span> <span class="mf">1.1</span> <span class="o">*</span> <span class="nb">max</span><span class="p">(</span><span class="n">x0</span><span class="p">,</span> <span class="n">y0</span><span class="p">)</span>
    
    <span class="k">for</span> <span class="n">star</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">stars</span><span class="p">:</span>
        <span class="n">star</span><span class="o">.</span><span class="n">distance</span> <span class="o">*=</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">nap</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="n">star</span><span class="o">.</span><span class="n">size</span> <span class="o">+=</span> <span class="mf">0.25</span> <span class="o">*</span> <span class="n">nap</span>
        
        <span class="k">if</span> <span class="p">(</span><span class="n">star</span><span class="o">.</span><span class="n">distance</span> <span class="o">&gt;</span> <span class="n">max_distance</span><span class="p">):</span>
            <span class="n">star</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">star</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">x0</span><span class="p">,</span> <span class="n">y0</span><span class="p">)</span>
        
    <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
    
    <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">canvas</span><span class="p">:</span>
        <span class="n">Mesh</span><span class="p">(</span><span class="n">fmt</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">vfmt</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">'triangles'</span><span class="p">,</span>
             <span class="n">indices</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">indices</span><span class="p">,</span> <span class="n">vertices</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">vertices</span><span class="p">,</span>
             <span class="n">texture</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">texture</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>首先星星从屏幕中央产生之后，我们计算最大距离<code>max_distance</code>。然后，我们重复星星列表，让它们运动起来，然后不断放大。超出屏幕的星星被重置。</p>
<p>函数的最后看着很熟悉，那是前面讲过的渲染技巧。调用<code>canvas.clear()</code>是必须的，但是每次调用都增加一个新的匹配（Mesh），极快的推送到显卡上进行处理。</p>
<p>代码的最后内容是<code>Star.update()</code>方法。它更像星星的四个顶点，把新的坐标值写到<code>vertices</code>数值中：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [ ]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="k">def</span> <span class="nf">iterate</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">j</span><span class="p">,</span>
                 <span class="bp">self</span><span class="o">.</span><span class="n">j</span> <span class="o">+</span> <span class="mi">4</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">sf</span><span class="o">.</span><span class="n">vsize</span><span class="p">,</span>
                 <span class="bp">self</span><span class="o">.</span><span class="n">sf</span><span class="o">.</span><span class="n">vsize</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x0</span><span class="p">,</span> <span class="n">y0</span><span class="p">):</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">x0</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">distance</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">cos</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">angle</span><span class="p">)</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">y0</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">distance</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">angle</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">iterate</span><span class="p">():</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">sf</span><span class="o">.</span><span class="n">vertices</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p><code>iterate()</code>辅助函数用来提高代码可读性，看着有点多，其实读起来更方便。</p>
<p>为了完成程序迭代，整个内存映射进程会把序列化每一帧里大量的对象作为一个重要目标来处理，这会提高性能。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="写GLSL代码">写GLSL代码<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E5%86%99GLSL%E4%BB%A3%E7%A0%81">¶</a>
</h4>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>着色器代码和前面类似。点着色器代码：</p>
<div class="highlight"><pre><span></span><span class="n">attribute</span> <span class="n">vec2</span> <span class="n">vCenter</span><span class="p">;</span>
<span class="n">attribute</span> <span class="kt">float</span> <span class="n">vScale</span><span class="p">;</span>

<span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">tex_coord0</span> <span class="o">=</span> <span class="n">vTexCoords0</span><span class="p">;</span>
    <span class="n">mat4</span> <span class="n">move_mat</span> <span class="o">=</span> <span class="n">mat4</span>
        <span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="n">vCenter</span><span class="p">.</span><span class="n">x</span><span class="p">,</span>
        <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="n">vCenter</span><span class="p">.</span><span class="n">y</span><span class="p">,</span>
        <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span>
        <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">);</span>
    <span class="n">vec4</span> <span class="n">pos</span> <span class="o">=</span> <span class="n">vec4</span><span class="p">(</span><span class="n">vPosition</span><span class="p">.</span><span class="n">xy</span> <span class="o">*</span> <span class="n">vScale</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">*</span> <span class="n">move_mat</span><span class="p">;</span>
    <span class="n">gl_Position</span> <span class="o">=</span> <span class="n">projection_mat</span> <span class="o">*</span> <span class="n">modelview_mat</span> <span class="o">*</span> <span class="n">pos</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>我们通过<code>vScale</code>因子与顶点坐标值相乘来等比例放大，然后用<code>vCenter</code>属性把它们变换成位置。<code>move_mat</code>矩阵是变换矩阵，线性代数里的一种放射变换方法。</p>
<p>像素着色器代码：</p>
<div class="highlight"><pre><span></span><span class="kt">void</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">gl_FragColor</span> <span class="o">=</span> <span class="n">texture2D</span><span class="p">(</span><span class="n">texture0</span><span class="p">,</span> <span class="n">tex_coord0</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>最终的效果如下图所示：</p>
<p><img src="kbpic/8.10%20star.png" alt="star"></p>
<p>这样，满天星app就完成了，感受一下穿越的乐趣吧。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="总结">总结<a class="anchor-link" href="kivy-ch8-shaders-app.html#%E6%80%BB%E7%BB%93">¶</a>
</h3>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>这一章我们介绍了底层的OpenGL硬件加速方式，用GLSL实现了点，索引和着色器。</p>
<p>GPU直接编程是一个极其强大的概念，这种强大也需要大量付出。着色器比普通的Python代码要难得多，调试工作就更复杂了，也没有一个像Python的REPL那样方便的交互开发环境。也就是说，做应用的时候，写原始的GLSL代码是否必要并没有答案，只能因地制宜。</p>
<p>这章的例子只是一个简单教程，并不是能力测试。因为 GLSL非常难学，大量的书籍和在线教程都已经介绍过它，这里的内容不足以完整的介绍OpenGL的内容，若感兴趣可以看看。</p>
<p>现在，我们算是入门了。下一章我们利用这章的代码来做一个更好玩的应用，一个酷炫的射击游戏。</p>
<p><a href="kbpic/src/8_Starfield">源代码</a></p>

</div>
</div>
</div>
    </div>
  </div>

    </div>
    <aside class="postpromonav"><nav><ul itemprop="keywords" class="tags">
<li><a class="tag p-category" href="../categories/chs.html" rel="tag">CHS</a></li>
            <li><a class="tag p-category" href="../categories/ipython.html" rel="tag">ipython</a></li>
            <li><a class="tag p-category" href="../categories/kivy.html" rel="tag">Kivy</a></li>
            <li><a class="tag p-category" href="../categories/python.html" rel="tag">Python</a></li>
        </ul>
<ul class="pager hidden-print">
<li class="previous">
                <a href="frequentism-and-bayesianism-chs-iii.html" rel="prev" title="frequentism-and-bayesianism-chs-iii">Previous post</a>
            </li>
            <li class="next">
                <a href="kivy-perface.html" rel="next" title="kivy-perface">Next post</a>
            </li>
        </ul></nav></aside><script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script><script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        processEscapes: true
    },
    displayAlign: 'center', // Change this to 'center' to center equations.
    "HTML-CSS": {
        styles: {'.MathJax_Display': {"margin": 0}}
    }
});
</script></article>
</div>
        <!--End of body content-->

        <footer id="footer">
            Contents © 2017         <a href="mailto:muxuezi@gmail.com">Tao Junjie</a> - Powered by         <a href="https://getnikola.com" rel="nofollow">Nikola</a>         
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0">
<img alt="Creative Commons License BY-NC-SA" style="border-width:0; margin-bottom:12px;" src="http://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png"></a>
            
        </footer>
</div>
</div>


            <script src="../assets/js/all-nocdn.js"></script><script>$('a.image-reference:not(.islink) img:not(.islink)').parent().colorbox({rel:"gal",maxWidth:"100%",maxHeight:"100%",scalePhotos:true});</script><!-- fancy dates --><script>
    moment.locale("en");
    fancydates(0, "YYYY-MM-DD HH:mm");
    </script><!-- end fancy dates --><script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51330059-1', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>
